import { useAppStore } from "~/store/appStore";
import { request, useMyFetch } from "./base";
import type { QueryPage, Blog } from "@/types";

export function create(param: {
  title: string;
  desc: string;
  text: string;
  tags: string;
}) {
  return request<Blog>({
    url: "/blog",
    method: "post",
    data: param,
  });
}

export function update(param: {
  id: string | number;
  title?: string;
  desc?: string;
  text?: string;
  tags?: string;
}) {
  return request<Blog>({
    url: `/blog/${param.id}`,
    method: "patch",
    data: param,
  });
}

export function del(id: string | number) {
  return request<Blog>({
    url: `/blog/${id}`,
    method: "delete",
  });
}
export function uploadImage(param: File, key = "file") {
  const fromData = new FormData();
  fromData.append(key, param);
  return request<{ url: string }>({
    url: "/file",
    method: "post",
    data: fromData,
  });
}
export function useTags() {
  return useMyFetch<string[]>("/blog/tags", {
    key: "tags",
    cache: "force-cache",
  });
}
export const GetBlogUrl = "/blog";
export function useBlog(queryUrl: Ref<string>) {
  return useMyFetch<QueryPage<Blog>>(queryUrl, {
    cache: "force-cache",
  });
}

export function useBlogById(id: string|number) {
  return useMyFetch<Blog>(`/blog/${id}`, {
    cache: "force-cache",
  });
}

export function good(id?: number) {
  if (!id) return Promise.resolve();
  const appStore = useAppStore();
  const inclued = appStore.goodList.includes(id);
  if (inclued) {
    return goodDec(id).then(() => {
      appStore.goodList = appStore.goodList.filter((i) => i !== id);
      appStore.saveGoods();
    });
  }
  return _good(id).then(() => {
    appStore.goodList.push(id);
    appStore.saveGoods();
  });
}

export function _good(id: number) {
  return request({
    url: `/blog/good/${id}`,
    method: "get",
  });
}

export function goodDec(id: number) {
  return request({
    url: `/blog/goodDec/${id}`,
    method: "get",
  });
}
